package com.youdelu.road.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.google.gson.Gson;
import com.youdelu.road.bean.Attr;
import com.youdelu.road.bean.FileDir;

import java.util.HashMap;
import java.util.Map;

public class BroadcastManager {

    private Context mContext;
    private static BroadcastManager instance;
    private Map<String, BroadcastReceiver> receiverMap;
    private static Gson gson ;

    /**
     * 构造方法
     *
     * @param context
     */
    private BroadcastManager(Context context) {
        this.mContext = context.getApplicationContext();
        receiverMap = new HashMap<String, BroadcastReceiver>();
    }

    /**
     * [获取BroadcastManager实例，单例模式实现]
     *
     * @param context
     * @return
     */
    public static BroadcastManager getInstance(Context context) {
        if (instance == null) {
            synchronized (BroadcastManager.class) {
                if (instance == null) {
                    instance = new BroadcastManager(context);
                    gson = new Gson();
                }
            }
        }
        return instance;
    }

    /**
     * 添加
     *
     * @param
     */
    public void addAction(String action, BroadcastReceiver receiver) {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(action);
            mContext.registerReceiver(receiver, filter);
            receiverMap.put(action, receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送广播
     *
     * @param action
     * @param s
     */
    public void sendBroadcast(String action,int id, String name,String path) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra("id",id);
        intent.putExtra("name",name);
        intent.putExtra("path",path);
        mContext.sendBroadcast(intent);
    }

    /**
     * 发送位置广播
     * @param action
     * @param attr
     */
    public void sendBroadcast(String action, Attr attr) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra("attr",gson.toJson(attr));
        mContext.sendBroadcast(intent);
    }


    /**
     * 销毁广播
     *
     * @param action
     */
    public void destroy(String action) {
        if (receiverMap != null) {
            BroadcastReceiver receiver = receiverMap.remove(action);
            if (receiver != null) {
                mContext.unregisterReceiver(receiver);
            }
        }
    }
}
